import 'dart:async';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:FiduMart/core/utils/logger.dart';
import 'package:FiduMart/localization/app_export.dart';

class CountDownButton extends StatefulWidget {
  Function? onTimerFinish;

  final Function onPressed;

  CountDownButton({this.isEnable = true, this.onTimerFinish, required this.onPressed, this.disableText = ''});

  //控制按钮是否可点击
  var isEnable;

  var disableText;

  @override
  State<StatefulWidget> createState() => _TimerCountDownWidgetState();
}

class _TimerCountDownWidgetState extends State<CountDownButton> {
  Timer? _timer;
  int _countdownTime = 0;

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: () {
        if (_countdownTime > 0) {
          return;
        }
        if (!widget.isEnable) {
          Fluttertoast.showToast(msg: widget.disableText);
          return;
        }

        _startCountdownTimer();
      },
      child: Text(
        _countdownTime > 0 ? '$_countdownTime'+'get_code_again'.tr : 'get_code'.tr,
        style: TextStyle(
          fontSize: 14,
          color: _countdownTime > 0 ? Colors.grey : ColorConstant.colorFFAD4AFF,
        ),
      ),
    );
  }

  Future<void> _startCountdownTimer() async {
    bool success = await widget.onPressed();
    if (!success) {
      return;
    }
    setState(() {
      _countdownTime = 60;
    });

    _timer = Timer.periodic(
      const Duration(seconds: 1),
      (Timer timer) {
        if (_countdownTime < 1) {
          widget.onTimerFinish?.call();
          timer.cancel();
        } else {
          setState(() {
            _countdownTime -= 1;
          });
        }
      },
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}
